import React, { useState } from 'react';
import styles from './index.less';
import { Drawer, Spin, message } from 'antd';
import { useSetState } from 'ahooks';
import moment from 'moment';

import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import planIcon from '@/assets/img/plan_icon.png';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { YearlyMaintenancePlansEcharts } from '../../../components/Charts/index.js';
import { TABLECOLUMNS } from '../../../dictionary';
import { postQueryTendingPlanList, postQueryAllTendingPlan } from '../../../services';
import type {
  IStationsDataType,
  IFormValue,
  IIsLoadingType,
  IIsErrorType,
  IDealElementOptions,
  IDataListType,
  IMaintenancePlanModalType,
} from '../../../type';
import { formatJson, dealDataSource } from '../../../tool';
import { DrawerHeader, PlanList } from '../index';

interface IProps {
  /**
   * 全部交易单元
   */
  allStationData?: IStationsDataType;
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
  /**
   * 编辑检修计划表
   */
  onEdit?: (record: IDataListType, type: IMaintenancePlanModalType, onReview?: any) => void;
  /**
   * 按钮权限
   */
  buttonPermissions: any;
}

const YearlyMaintenancePlans = (props: IProps) => {
  const { visible = false, allStationData, onClose, onEdit, buttonPermissions } = props;
  const canEport =
    buttonPermissions.findIndex((item: any) => item.menuCode === 'MaintenancePlanExport') > -1;
  const [formValue, setFormValue] = useSetState<IFormValue>({});
  const [isLoading, setIsLoading] = useState<IIsLoadingType>({
    yearlyMaintenancePlansDateIsLoading: true,
    maintenanceScheduleIsLoading: true,
  });
  const [isError, setIsError] = useSetState<IIsErrorType>({
    yearlyMaintenancePlansDateIsError: false,
    maintenanceScheduleIsError: false,
  });
  const [maintenanceScheduleData, setMaintenanceScheduleData] = useState<IDataListType[]>([]);
  const [yearlyMaintenancePlansDateData, setYsearlyMaintenancePlansDateData] = useState<any>();

  // 检修计划表
  const getPostMaintenanceScheduleData = async (params: IFormValue) => {
    setIsLoading({
      maintenanceScheduleIsLoading: true,
    });
    const res = await postQueryTendingPlanList(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setMaintenanceScheduleData(res.data || []);
      setIsError({
        maintenanceScheduleIsError: false,
      });
    } else {
      setIsError({
        maintenanceScheduleIsError: true,
      });
      message.error(res.message || '系统异常');
    }
    setIsLoading({
      maintenanceScheduleIsLoading: false,
    });
  };

  // 检修计划格子图
  const getPostGetYearlyMaintenancePlansDate = async (params: IFormValue) => {
    setIsLoading({
      yearlyMaintenancePlansDateIsLoading: true,
    });
    const res = await postQueryAllTendingPlan(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setYsearlyMaintenancePlansDateData(res.data);
      setIsError({
        yearlyMaintenancePlansDateIsError: false,
      });
    } else {
      setIsError({
        yearlyMaintenancePlansDateIsError: true,
      });
      message.error(res.message || '系统异常');
    }
    setIsLoading({
      yearlyMaintenancePlansDateIsLoading: false,
    });
  };

  // 搜索数据
  const onSearch = async (params: IFormValue) => {
    setFormValue(params);
    getPostGetYearlyMaintenancePlansDate(params);
    getPostMaintenanceScheduleData(params);
  };

  // 点击日历图
  const handleEchartsEvent = (e: any) => {
    const _value = e?.value || [];
    const _date = _value[0];
    const _params: IFormValue = {
      ...formValue,
      startDate: _date,
      endDate: _date,
    };
    getPostMaintenanceScheduleData(_params);
  };

  // 取消
  const _onCancel = () => {
    onClose && onClose();
  };

  // 新增/编辑检修计划
  const onEditMaintenanceSchedule = async (
    record: IDataListType,
    maintenancePlanModalType: IMaintenancePlanModalType,
  ) => {
    onEdit &&
      onEdit(record, maintenancePlanModalType, () => {
        onSearch(formValue);
      });
  };
  const defaultRequest = async () => {
    const _params: IFormValue = {
      stationIdList: allStationData?.allKeys,
      planState: -1,
      startDate: moment().startOf('year').format('YYYY-MM-DD'),
      endDate: moment().endOf('year').format('YYYY-MM-DD'),
    };
    onSearch(_params);
  };
  React.useEffect(() => {
    if (visible) {
      defaultRequest();
    }
  }, [visible]);
  //导出检修计划表
  const exportMaintenancePlan = () => {
    if (!maintenanceScheduleData.length) return;
    if (!canEport) {
      return message.info('请联系管理员获取相关权限');
    }
    const data = dealDataSource(maintenanceScheduleData);
    const filename = '全部计划检修';
    const params: any = {
      header: ['全部检修计划'],
      data: [[]],
      filename,
    };
    const filterVal = TABLECOLUMNS.map((t, i) => {
      if (i > 0) {
        params.header.push('');
      }
      params.data[0].push(t.header);
      return t.key;
    });

    params.data = params.data.concat(formatJson(filterVal, data));
    export_json_to_excel(params);
  };
  return (
    <Drawer
      width={1400}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>全部检修计划</span>
        </div>
      }
      footer={null}
    >
      <div className={styles.container}>
        <div className={styles.header}>
          <DrawerHeader
            defaultRequest={defaultRequest}
            allStationData={allStationData}
            values={formValue}
            onSearch={onSearch}
            onEdit={onEditMaintenanceSchedule}
            exportMaintenancePlan={exportMaintenancePlan}
            canEport={!maintenanceScheduleData.length || !canEport}
          />
        </div>
        <div className={styles.center}>
          {isLoading.yearlyMaintenancePlansDateIsLoading ? (
            <Spin />
          ) : isError.yearlyMaintenancePlansDateIsError ? (
            <TRDefault type={'emptysm'} message={'系统异常'} />
          ) : yearlyMaintenancePlansDateData ? (
            <div className={styles.yearlyMaintenancePlansDate}>
              <YearlyMaintenancePlansEcharts
                data={yearlyMaintenancePlansDateData}
                startDate={formValue?.startDate}
                endDate={formValue?.endDate}
                handleObj={{
                  handleName: 'click',
                  handleKeys: 'series',
                  handleEvent: (e: any) => {
                    handleEchartsEvent(e);
                  },
                }}
              />
            </div>
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
        <div className={styles.bottom}>
          {isLoading.maintenanceScheduleIsLoading ? (
            <Spin />
          ) : isError.maintenanceScheduleIsError ? (
            <TRDefault type={'emptysm'} message={'系统异常'} />
          ) : maintenanceScheduleData?.length ? (
            <div className={styles.maintenanceSchedule}>
              <PlanList
                dataSource={maintenanceScheduleData || []}
                onEdit={onEditMaintenanceSchedule}
                overhaul
                formValue={formValue}
                onSearch={onSearch}
              />
            </div>
          ) : (
            <TRDefault type={'emptysm'} message={'暂无数据'} />
          )}
        </div>
      </div>
    </Drawer>
  );
};

export default YearlyMaintenancePlans;
